<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OpenAI Chat Demo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: #f5f5f5;
        }
        .chat-container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
        }
        .chat-box {
            height: 500px;
            overflow-y: auto;
            border: 1px solid #eee;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 5px;
            white-space: pre-wrap;
            font-family: monospace;
        }
        .user-message {
            background: #e3f2fd;
            /* margin-left: 20%; */
        }
        .ai-message {
            background: #f5f5f5;
            /* margin-right: 20%; */
        }
        .input-container {
            display: flex;
            gap: 10px;
        }
        textarea {
            flex-grow: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            resize: none;
            height: 60px;
            font-family: monospace;
        }
        button {
            padding: 10px 20px;
            background: #2196f3;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s;
        }
        button:hover {
            background: #1976d2;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .api-key-container {
            margin-bottom: 20px;
        }
        .api-key-container>select {
            box-sizing: border-box;
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="api-key-container">
            <select id="modeName">
                <option value="navinfo deepseek-r1">navinfo deepseek-r1</option>
                <option value="gpt-4">gpt-4</option>
                <option value="gpt-4o">gpt-4o</option>
                <option value="gpt-4o-mini">gpt-4o-mini</option>
                <option value="gpt-3.5-turbo">gpt-3.5-turbo</option>
                <option value="deepseek-chat">navinfo deepseek-chat</option>
                <option value="deepseek-coder">navinfo deepseek-coder</option>
            </select>
            <select id="apiKey">
                <option value="sk-9ksFu6qUIHrQZFo_TjjUUnMro-iObUnm07QzAi_xZfmWAAKITFNHYveaTb8">navinfo deepseek</option>
                <option value="sk-2qHMgOvsbppxJM11ea5oPgWtFtpViu5ghl7QlsLN8CPHdpGn">默认API密钥</option>
            </select>
            <select id="apiUrl">
                <option value="https://llmapi-aiinfra.navinfo.com/v1/chat/completions">navinfo deepseek</option>
                <option value="https://api.fe8.cn/v1/chat/completions">默认API地址</option>
            </select>
        </div>
        <div class="chat-box" id="chatBox"></div>
        <div class="input-container">
            <textarea id="userInput" placeholder="输入你的消息..."></textarea>
            <button onclick="sendMessage()" id="sendButton">发送</button>
        </div>
    </div>

    <script>
        const chatBox = document.getElementById('chatBox');
        const userInput = document.getElementById('userInput');
        const sendButton = document.getElementById('sendButton');
        const modeNameInput = document.getElementById('modeName');
        const apiKeyInput = document.getElementById('apiKey');
        const apiUrlInput = document.getElementById('apiUrl');

        const OPENAI_API_KEY = 'sk-2qHMgOvsbppxJM11ea5oPgWtFtpViu5ghl7QlsLN8CPHdpGn';
        const OPENAI_API_URL = 'https://api.fe8.cn/v1/chat/completions';

        async function sendMessage() {
            const message = userInput.value.trim();
            const modeName = modeNameInput.value;
            const apiKey = apiKeyInput.value || OPENAI_API_KEY;
            const apiUrl = apiUrlInput.value || OPENAI_API_URL;
            if (!message || !apiKey) {
                addMessageToChat('ai', '请输入消息和OpenAI API密钥。');
                return;
            }

            sendButton.disabled = true;
            userInput.disabled = true;

            addMessageToChat('user', message);
            userInput.value = '';
            console.log('modeName:', modeName);
            console.log('apiKey:', apiKey);
            console.log('apiUrl:', apiUrl);
            
            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`
                    },
                    body: JSON.stringify({
                        // model: "gpt-4o-mini",
                        model: modeName,
                        messages: [
                            {
                                role: "system",
                                content: "介绍下当前的API模型"
                            },
                            {
                                role: "user", 
                                content: message
                            }],
                        stream: true
                    })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let currentMessageDiv = null;
                let markdownText = '';

                while (true) {
                    const {value, done} = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6);
                            if (data === '[DONE]') continue;

                            try {
                                const parsed = JSON.parse(data);
                                const content = parsed.choices[0].delta.content;
                                
                                if (content) {
                                    if (!currentMessageDiv) {
                                        currentMessageDiv = document.createElement('div');
                                        currentMessageDiv.className = 'message ai-message';
                                        chatBox.appendChild(currentMessageDiv);
                                    }
                                    markdownText += content;
                                    currentMessageDiv.innerHTML = marked.parse(markdownText);
                                    // 添加复制按钮
                                    const copyButton = document.createElement('button');
                                    copyButton.textContent = '复制';
                                    copyButton.onclick = () => {
                                        navigator.clipboard.writeText(markdownText);
                                    };
                                    currentMessageDiv.appendChild(copyButton);
                                    chatBox.scrollTop = chatBox.scrollHeight;
                                }
                            } catch (e) {
                                console.error('解析错误:', e);
                            }
                        }
                    }
                }
            } catch (error) {
                addMessageToChat('ai', `Error: ${error.message}`);
            } finally {
                sendButton.disabled = false;
                userInput.disabled = false;
                userInput.focus();
            }
        }

        function addMessageToChat(role, content) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}-message`;
            if (role === 'ai') {
                messageDiv.innerHTML = marked.parse(content);
            } else {
                messageDiv.textContent = content;
            }
            chatBox.appendChild(messageDiv);
            chatBox.scrollTop = chatBox.scrollHeight;
        }

        userInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
</body>
</html>
